<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="危废名称">
                <el-input v-model="queryParams.wasteName" placeholder="请输入危废名称" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="批次号码">
                <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号码" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="危废状态">
                <el-select v-model="queryParams.wasteStatus" placeholder="请选择危废状态">
                    <el-option v-for="dict in wasteFlowStatusList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="申报人">
                <el-input v-model="queryParams.declareBy" placeholder="请输入申报人" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="申报日期">
                <el-date-picker v-model="daterangeDeclareDate" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="收运者" prop="createBy">
                <el-input v-model="queryParams.createBy" placeholder="请输入收运者" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="收运日期">
                <el-date-picker v-model="daterangeCollectDate" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="success" plain size="mini" :disabled="collectDisabled" @click="handleCollect" v-hasPermi="['business:wasteCollect:add']">收运</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain size="mini" :disabled="revertDisabled" @click="handleDelete" v-hasPermi="['business:wasteCollect:remove']">撤销</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['business:wasteCollect:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wasteCollectList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column label="危废收运明细ID" align="center" prop="wasteCollectDetailId" v-if="false" />
            <el-table-column label="危废申报ID" align="center" prop="wasteDeclareId" v-if="false" />
            <el-table-column label="批次号码" align="center" prop="batchNumber" width="180" />
            <el-table-column label="状态" align="center" prop="status" width="100" :formatter="wasteFlowStatusFormat" />
            <el-table-column type="expand">
                <template slot-scope="props">
                    <keep-alive>
                        <waste-info-card :row="props.row" />
                    </keep-alive>
                </template>
            </el-table-column>
            <el-table-column label="危废名称" align="left" prop="wasteName"></el-table-column>
            <el-table-column label="预估重量" align="center" prop="wasteDiscreetWeight" width="120" />
            <el-table-column label="申报人" align="center" prop="declareBy" width="100" />
            <el-table-column label="申报日期" align="center" prop="declareDate" width="120" />
            <el-table-column label="收运人" align="center" prop="collector" width="100" />
            <el-table-column label="收运日期" align="center" prop="collectDate" width="120">
            </el-table-column>
            <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.status === 10" size="mini" type="text" @click="handleCollect(scope.row)" v-hasPermi="['business:wasteCollect:add']">收运</el-button>
                    <el-button v-if="scope.row.status === 20" size="mini" type="text" @click="handleDelete(scope.row)" v-hasPermi="['business:wasteCollect:remove']">撤销</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改危废收运对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item v-show="false" label="申报id">
                    <el-input disabled v-model="form.wasteDeclareIds" />
                </el-form-item>
                <el-form-item label="收运日期" prop="collectDate">
                    <el-date-picker clearable size="small" v-model="form.collectDate" :picker-options="pickerOptions" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择收运日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listWasteCollect,
    delWasteCollect,
    addWasteCollect,
    exportWasteCollect,
} from "@/api/business/wasteCollect";

import WasteInfoCard from "@/views/business/wasteInfoCard";
import { mapActions, mapGetters } from "vuex";

export default {
    name: "WasteCollect",
    components: { WasteInfoCard },
    data() {
        return {
            //按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 选中数据的CollectIDS
            collectDetailIds: [],
            // 子表选中数据
            checkedEwmsWasteCollectDetail: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 收运按钮禁用标识
            collectDisabled: true,
            // 撤销按钮禁用标识
            revertDisabled: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 危废收运表格数据
            wasteCollectList: [],
            // 危废收运明细表格数据
            ewmsWasteCollectDetailList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 申报日期范围
            daterangeDeclareDate: [],
            // 收运日期范围
            daterangeCollectDate: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                collectDate: undefined,
                createBy: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                collectDate: [
                    {
                        required: true,
                        message: "收运日期不能为空",
                        trigger: "blur",
                    },
                ],
            },
            minDateTimeMsec: 0,
        };
    },
    created() {
        this.getList();
        // this.$store.dispatch("initDataForWasteInfoCard");
        this.initDictData();
    },
    computed: {
        ...mapGetters(["wasteFlowStatusOptions"]),
        wasteFlowStatusList() {
            return this.wasteFlowStatusOptions.filter(item => parseInt(item.dictValue) < 30);
        },
        pickerOptions() {
            const that = this;
            return {
                disabledDate: function (time) {
                    let curDate = (new Date()).getTime();
                    const sevenDayMsec = 7 * 24 * 3600 * 1000;
                    let beforeSevenDay = curDate - sevenDayMsec;
                    that.minDateTimeMsec = (that.minDateTimeMsec === 0 ? beforeSevenDay : that.minDateTimeMsec);
                    return time.getTime() > Date.now() || time.getTime() < that.minDateTimeMsec;;
                }
            }
        }
    },
    methods: {
        ...mapActions({
            initDictData: "initDataForWasteInfoCard",
        }),
        /** 查询危废收运列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (
                null != this.daterangeDeclareDate &&
                "" != this.daterangeDeclareDate
            ) {
                this.queryParams.params["beginDeclareDate"] =
                    this.daterangeDeclareDate[0];
                this.queryParams.params["endDeclareDate"] =
                    this.daterangeDeclareDate[1];
            }
            if (
                null != this.daterangeCollectDate &&
                "" != this.daterangeCollectDate
            ) {
                this.queryParams.params["beginCollectDate"] =
                    this.daterangeCollectDate[0];
                this.queryParams.params["endCollectDate"] =
                    this.daterangeCollectDate[1];
            }
            listWasteCollect(this.queryParams).then((response) => {
                this.wasteCollectList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },

        // 危废状态字典翻译
        wasteFlowStatusFormat(row, column) {
            const status = row.status === 30 ? 20 : row.status;
            return this.selectDictLabel(
                this.wasteFlowStatusOptions,
                status
            );
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                wasteCollectId: undefined,
                collectDate: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                remark: undefined,
            };
            this.ewmsWasteCollectDetailList = [];
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeCollectDate = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.wasteDeclareId);
            this.collectDetailIds = selection.map((item) => item.wasteCollectId);
            if (selection.length === 0) {
                this.collectDisabled = true;
                this.revertDisabled = true;
            } else {
                const collectedCount = selection.filter((item) => item.status === 20).length;
                this.collectDisabled = collectedCount > 0;
                const preCollectedCount = selection.filter((item) => item.status === 10).length;
                this.revertDisabled = preCollectedCount > 0;
            }
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加危废收运";
        },
        /** 收运按钮操作 */
        handleCollect(row) {
            this.loading = true;
            // this.reset();
            const wasteDeclareId = row.wasteDeclareId || this.ids.join(",");
            let wasteDeclareDate = "";
            if (row.wasteDeclareId === null || row.wasteDeclareId === undefined || row.wasteDeclareId === '') {
                const declareDateArr = this.wasteCollectList.filter(item => this.ids.indexOf(item.wasteDeclareId) !== -1).map(item => item.declareDate);
                declareDateArr.sort().reverse();
                wasteDeclareDate = declareDateArr[0];
            } else {
                wasteDeclareDate = row.declareDate;
            }

            if (wasteDeclareDate) {
                this.minDateTimeMsec = Date.parse(`${wasteDeclareDate} 00:00:00`);
            }

            this.loading = false;
            this.form = {
                wasteDeclareIds: wasteDeclareId,
                collectDate: this.parseTime(new Date()),
            };
            this.open = true;
            this.title = "危废收运";
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.buttonLoading = true;
                    addWasteCollect(this.form).then((response) => {
                        this.buttonLoading = false;
                        this.msgSuccess("收运成功");
                        this.open = false;
                        this.getList();
                    });
                }
            });
        },
        /** 撤销按钮操作 */
        handleDelete(row) {
            const wasteCollectDetailId = row.wasteCollectDetailId || this.collectDetailIds;
            this.$confirm(
                '是否确认撤销?',
                "警告",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            )
                .then(() => {
                    this.loading = true;
                    return delWasteCollect(wasteCollectDetailId);
                })
                .then(() => {
                    this.loading = false;
                    this.getList();
                    this.msgSuccess("撤销成功");
                })
                .catch(() => { });
        },
        /** 危废收运明细序号 */
        rowEwmsWasteCollectDetailIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 危废收运明细添加按钮操作 */
        handleAddEwmsWasteCollectDetail() {
            let obj = {};
            obj.wasteDeclareId = "";
            obj.batchNumber = "";
            obj.remark = "";
            this.ewmsWasteCollectDetailList.push(obj);
        },
        /** 危废收运明细删除按钮操作 */
        handleDeleteEwmsWasteCollectDetail() {
            if (this.checkedEwmsWasteCollectDetail.length == 0) {
                this.$alert("请先选择要删除的危废收运明细数据", "提示", {
                    confirmButtonText: "确定",
                });
            } else {
                this.ewmsWasteCollectDetailList.splice(this.checkedEwmsWasteCollectDetail[0].index - 1, 1);
            }
        },
        /** 单选框选中数据 */
        handleEwmsWasteCollectDetailSelectionChange(selection) {
            if (selection.length > 1) {
                this.$refs.ewmsWasteCollectDetail.clearSelection();
                this.$refs.ewmsWasteCollectDetail.toggleRowSelection(
                    selection.pop()
                );
            } else {
                this.checkedEwmsWasteCollectDetail = selection;
            }
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm("是否确认导出所有危废收运数据项?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.exportLoading = true;
                    return exportWasteCollect(queryParams);
                })
                .then((response) => {
                    this.download(response.msg);
                    this.exportLoading = false;
                })
                .catch(() => { });
        },
    },
};
</script>

<style>
.demo-table-expand {
    font-size: 0;
    padding: 0px 0px 0px 150px;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}
</style>